import dayjs from 'dayjs';
import { inject } from 'vue';
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';

let http;
let message;
let store = null;
let route = null;
let router = null;
let eventBus = null;

/**
 * 获取axios http请求对象
 * 
 * @returns axios http请求对象
 */
function getHttp () {
  return http || (http = inject('$http'));
}

function getMessage () {
  return message || (message = inject('$message'));
}

/**
 * 获取vuex对象
 *  
 * @returns vuex对象
 */
function getStore () {
  return store || (store = useStore());
}

function getRoute () {
  return route || (route = useRoute());
}

/**
 * 获取vue-router对象
 * 
 * @returns vue-router对象
 */
function getRouter () {
  return router || (router = inject('$router'));
}

function getEventBus () {
  return eventBus || (eventBus = inject('$eventBus'));
}

/**
 * 获取当前用户ID
 * 
 * @returns 当前用户ID
 */
function getCurrentUserId () {
  return getStore().getters.currentUserId()
}

function getApi (key, needUserId) {
  key = key || '';

  return key.startsWith('/') ? key : getStore().getters.getApi(key, needUserId);
}

function dateFormat (value, fmt) {
  if (!value) {
    return '';
  }

  fmt = fmt || 'yyyy-MM-dd';
  let date = new Date(value);
  if (date.getFullYear() == 1) {
    return '';
  }
  let o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
    "q+": Math.floor((date.getMonth() + 3) / 3),
    "S": date.getMilliseconds()
  };

  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  }

  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }

  return fmt;
}

function urlParam (data) {
  let param = '';
  let index = 0;
  for (let i in data) {
    if (index == 0) {
      param += i + "=" + data[i];
    }
    else {
      param += "&" + i + "=" + data[i];
    }
    index++;
  }
  return param;
}

//将null值转化为空字符串
function nullToStr (data) {
  if (typeof data != 'object' || data === null || data === 'null') {
    data = '';
    return data;
  } else {
    for (let x in data) {
      if (data[x] === null || data[x] === 'null') { // 如果是null 把直接内容转为 ''
        data[x] = '';
      } else {
        if (Array.isArray(data[x])) { // 是数组遍历数组 递归继续处理
          data[x] = data[x].map(z => {
            return nullToStr(z);
          });
        }
        if (typeof (data[x]) === 'object') { // 是json 递归继续处理
          data[x] = nullToStr(data[x])
        }
      }
    }
    return data;
  }
}

//金额格式化方法
function clearNoNum (obj) {
  //将数字变成字符串
  obj = obj + '';
  let varStr = obj[0];
  //先把非数字的都替换掉，除了数字和.
  obj = obj.replace(/[^\d.]/g, "");
  //保证只有出现一个.而没有多个.
  obj = obj.replace(/\.{2,}/g, ".");
  //必须保证第一个为数字而不是.
  obj = obj.replace(/^\./g, "");
  //保证.只出现一次，而不能出现两次以上
  obj = obj.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
  //只能输入两个小数
  obj = obj.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
  if (varStr == "-") {
    obj = varStr + obj;
  }

  return Number(obj);
}

/*
* 参数说明：
* number：要格式化的数字
* decimals：保留几位小数
* dec_point：小数点符号
* thousands_sep：千分位符号
*/
function numberFormat (number, decimals, dec_point, thousands_sep) {
  number = (number + '').replace(/[^0-9+-Ee.]/g, '');
  var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
    dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
    s = '',
    toFixedFix = function (n, prec) {
      var k = Math.pow(10, prec);
      return '' + (n * k) / k;
    };
  //var test = toFixedFix(n, prec);
  s = (prec ? toFixedFix(n, prec) : '' + Math.floor(n)).split('.');
  var re = /(-?\d+)(\d{3})/;
  //console.log(s)
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, "$1" + sep + "$2");
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || '';
    s[1] += new Array(prec - s[1].length + 1).join('0');
  }
  return s.join(dec);
}

//表单验证
function isFormValid () {
  let result = { code: 0, message: '' };
  let requiredHtml = document.getElementsByClassName('van-field__label--required');
  for (let i = 0; i < requiredHtml.length; i++) {
    //文本类型
    let localName = requiredHtml[i].nextSibling.firstChild.nextSibling.firstChild.localName;
    //文本值
    let value = ''
    if (localName == "div") {
      value = requiredHtml[i].nextSibling.firstChild.nextSibling.firstChild.innerText;
    }
    else if (localName == 'input' || localName == 'textarea') {
      value = requiredHtml[i].nextSibling.firstChild.nextSibling.firstChild.value;
    }
    if (value == '') {
      let title = requiredHtml[i].innerText;
      result.code = -1;
      result.message = title.replace("：", "").replace(":", "") + '不能为空！'
      break
    }
  }
  return result
}

function getCurrency (num) {
  num = num.toString().replace(/\$|\,/g, '');
  if (isNaN(num))
    num = "0";
  let sign = (num == (num = Math.abs(num)));
  num = Math.floor(num * 100 + 0.50000000001);
  let cents = num % 100;
  num = Math.floor(num / 100).toString();
  if (cents < 10)
    cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
    num = num.substring(0, num.length - (4 * i + 3)) + ',' +
      num.substring(num.length - (4 * i + 3));
  return (((sign) ? '' : '-') + num + '.' + cents);
}

//获取某个时间的前一个月
function getLastMonth (date) {
  var currentYear = date.getFullYear();
  var currentMonth = date.getMonth() + 1;
  var lastMonth = date.getMonth();
  var currentDate = date.getDate();
  var prevCurrentYear = 0;
  var prevCurrentMonth = 0;
  if (currentMonth == 0) {
    prevCurrentYear = currentYear - 1;
    prevCurrentMonth = 12;
  } else {
    prevCurrentYear = currentYear;
    prevCurrentMonth = currentMonth - 1;
  }
  var lastmonth = prevCurrentYear + "-" + prevCurrentMonth + "-" + currentDate

  return lastmonth;
}

function getExplorer () {
  const ua = window.navigator.userAgent.toLowerCase();
  const isExplorer = (exp) => {
    return ua.indexOf(exp.toLowerCase()) > -1;
  }

  if (isExplorer('MSIE')) {
    return 'IE';
  } else if (isExplorer('Firefox')) {
    return 'Firefox';
  } else if (isExplorer('Chrome')) {
    return 'Chrome';
  } else if (isExplorer('Opera')) {
    return 'Opera';
  } else if (isExplorer('Safari')) {
    return 'Safari';
  } else if (isExplorer('Edge')) {
    return 'Edge';
  } else if (isExplorer('QQBrowser')) {
    return 'QQ Browser';
  }
}

function fillDatas (target, sources) {
  let tkeys = Object.keys(target);

  tkeys.forEach(e => delete target[e]);

  if (sources) {
    let skeys = Object.keys(sources);

    skeys.forEach(e => target[e] = sources[e]);
  }
}

function friendlyNumbers (number) {
  if (Number.isNaN(number)) {
    return '--';
  }

  let num = parseFloat(number);

  if (Number.isNaN(num)) {
    return '--';
  }

  if (num <= 10000) {
    return num;
  } else if (num > 10000 && num <= 100000000) {
    return (num / 10000).toFixed(2) + '万';
  } else {
    return (num / 100000000).toFixed(4) + '亿';
  }
}

export default {
  getApi,
  getHttp,
  getStore,
  getRoute,
  getRouter,
  getMessage,
  getEventBus,
  dateFormat,
  getCurrentUserId,
  urlParam,
  nullToStr,
  clearNoNum,
  numberFormat,
  isFormValid,
  getCurrency,
  getLastMonth,
  getExplorer,
  fillDatas,
  friendlyNumbers
};

export function friendlyDate (date) {
  if (!date) {
    return '--';
  }

  return dayjs(date).format('YYYY-MM-DD');
}

export function friendlyDateTime (date) {
  if (!date) {
    return '--';
  }

  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}

export function getDate () {
  return dayjs().format('YYYY-MM-DD');
}

export function getDateTime () {
  return dayjs().format('YYYY-MM-DD HH:mm:ss');
}

export function isMobile() {
  return /ipad|harmonyos|iphone os|midp|rv:1.2.2.3|ucweb|android|windows ce| windows mobile/.test(window.navigator.userAgent.toLowerCase());
}